package com.example.recordingpen_datacollection.config;

import com.example.recordingpen_datacollection.config.Interceptor.RateLimitInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * @Desc 解决高版本无法兼容 swagger2 的问题
 *       如此配置之后，就可通过 http://127.0.0.1:8080/doc.html 去访问 swagger-ui.html
 *       http://localhost:8080/swagger-ui.html#/
 */

@Configuration
//@EnableSwagger2
public class WebMvcConfigurer extends WebMvcConfigurationSupport {

    @Autowired
    private RateLimitInterceptor rateLimitInterceptor;
    @Autowired
    private RateLimitConfig rateLimitConfig;
//    @Autowired
//    private RateLimitInterceptor rateLimitInterceptor;
//
//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        registry.addInterceptor(rateLimitInterceptor)
//                .addPathPatterns("/aiconsult/text")
//                .addPathPatterns("/aiconsult/text2"); // 指定需要拦截的URL模式
//    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        rateLimitConfig.addRateLimit("/aiconsult/text", 10); // 例如，/api/limited1/ 下每分钟最多10次请求
        rateLimitConfig.addRateLimit("/aiconsult/text2", 20); // 例如，/api/limited2/ 下每分钟最多20次请求
        rateLimitConfig.addRateLimit("/aiconsult/aiCounseling", 60); // 例如，/api/limited2/ 下每分钟最多60次请求
        registry.addInterceptor(rateLimitInterceptor)
                .addPathPatterns("/**"); // 拦截所有请求，但拦截逻辑中会根据路径判断是否应用速率限制
    }

    /**
     * 发现如果继承了WebMvcConfigurationSupport，则在yml中配置的相关内容会失效。 需要重新指定静态资源
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html", "doc.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }

}
